const Redis = require('ioredis');
const config = require('../config');

const redis = new Redis();

const rateLimitMiddleware = async (req, res, next) => {
  try {
    const today = new Date().toISOString().slice(0, 10);
    const redisKey = `${config.redis.rateLimitKey}:${today}`;
    const requestCount = await redis.get(redisKey);

    if (requestCount && parseInt(requestCount) >= config.redis.maxRequestsPerDay) {
      return res.status(200).json({
        code: '429',
        data: { table: '', list: [] },
        msg: 'Daily request limit exceeded'
      });
    }

    await redis.incr(redisKey);
    await redis.expire(redisKey, 24 * 60 * 60);
    next();
  } catch (error) {
    console.error('Rate limit error:', error);
    next();
  }
};

module.exports = rateLimitMiddleware; 